#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import logging
from artists import Artist, Album, Song
from util import download_pic
from urllib.parse import quote

HEADERS = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) '
                         'Chrome/79.0.3945.88 Safari/537.36'}

# 获取access_token
ACCESS_TOKEN_URL = 'https://open.spotify.com/get_access_token?reason=transport&productType=web_player'

# 获取token需要的cookie
COOKIE = {
    "Cookie": "sp_t=83089d272ba49b9c8fa34ee704e434ed; sp_adid=6965475d-9c6a-4aeb-8f56-58edcffb0f14; cookieNotice=true; sp_phash=41024504b6f6d101ef2b2479c293db6651621926; sp_gaid=0088fcb616c7823bac12aca774c1a84af79a29cc332749ba74f525; _gcl_au=1.1.243086925.1583216371; _fbp=fb.1.1583216373265.1954981581; _scid=f1d6cc18-4e10-431d-8bbc-6e997296a08f; _hjid=92f71c0f-7166-4eb4-81f2-58c7f3b11162; sp_last_utm=%7B%22utm_campaign%22%3A%22wwwredirect%22%2C%22utm_source%22%3A%22play%22%7D; sp_m=bh-en; spot=%7B%22t%22%3A1583393368%2C%22m%22%3A%22bh-en%22%2C%22p%22%3Anull%7D; _ga_S35RN5WNT2=GS1.1.1583478901.6.0.1583478901.0; _ga=GA1.2.415369660.1583140665; __gads=ID=e5d42e245447d851:T=1583812291:S=ALNI_MZs9UHbmf6-riQhkzxNfhzCcSBGiw; sp_landing=https%3A%2F%2Fopen.spotify.com%2Fsearch%2Fed%2520sheeran; _gid=GA1.2.231984073.1587875276; _gat_gtag_UA_5784146_31=1; ki_t=1587875287215%3B1587875287215%3B1587875287215%3B1%3B1; ki_r=; _gat=1; sp_dc=AQAkKXmj0hzYYoF1l8sZs97dxfNZYAiQBefgm3nrjqMr6lvz1cHgYbwOuxbTdxJGHDIT-IX57hGgIX_PO2hRmjWw3p6o-LsryZq8VDy28XE; sp_key=92672910-08b9-4a11-b271-aa6a0bde525b"
}

# 搜索用户，第一个需要登录，第二个不需要登录
QUERY_URL = 'https://spclient.wg.spotify.com/searchview/km/v4/search/{0}'

# 查询歌手主页的信息（Get请求）
HOME_PAGE_DATA_URL = 'https://api-partner.spotify.com/pathfinder/v1/query?operationName=queryArtist&variables=%7B%22uri%22%3A%22{}%22%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%228ccebdab38821251f5b03be61a3484ac576d7ebd3a934c445ea8c318fe5d3ea2%22%7D%7D'

# 搜索专辑下的所有歌曲
ALBUMS_INFO_URL = 'https://api-partner.spotify.com/pathfinder/v1/query?operationName=queryAlbum&variables=%7B%22uri%22%3A%22{}%22%2C%22offset%22%3A0%2C%22limit%22%3A300%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%22f89efdfe3ddd447c9f3cc5c0be25dad3cab38b84e8d4e6897f274ceaaa577a89%22%7D%7D'

# 账号的一些信息
CLIENT_CREDS_ENV_VARS = {
    "client_id": "2c60cbec6e054248a9d99032df294406",
    "client_secret": "1bdf7e338fde4daaa36579c30eb3f111",
    "client_username": "spotify-spider",
    "redirect_uri": "http://localhost:8081/callback",
    "scope": "ugc-image-upload user-read-playback-state streaming user-read-private user-read-email playlist-read-collaborative user-modify-playback-state user-read-private playlist-modify-public user-library-modify user-top-read user-read-currently-playing user-follow-read app-remote-control user-read-recently-played playlist-modify-private user-follow-modify user-library-read"
}

# 创建Logger
logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                    level=logging.INFO)
logger = logging.getLogger()


# 获取acces_token
def get_access_token():
    logger.info("start get access_token")
    data = requests.get(ACCESS_TOKEN_URL, cookies=COOKIE).json()
    logger.info("access_token is %s", data)
    return data['accessToken']


# 主页搜索，返回符合name的歌手
def query(name, token):
    logger.info("start query artists")
    params = {'entityVersion': '2',
              'limit': '10',
              'imageSize': 'large',
              'catalogue': '',
              'country': 'HK',
              'username': 'lg0nidc4ov0qyu08qsjgcxfed',
              'locale': 'en',
              'platform': 'web'}
    HEADERS["Authorization"] = "Bearer " + token
    # ip = get_ip()
    # 防止429错误
    # logger.info('query name ip is -> %s', ip)
    # proxies = {'http': 'socks5://{}'.format(ip), 'https': 'socks5://{}'.format(ip)}
    # request = requests.get(QUERY_URL.format(name), headers=HEADERS, proxies=proxies, params=params)
    request = requests.get(QUERY_URL.format(quote(name, 'utf-8')), params=params, headers=HEADERS)
    print(QUERY_URL.format(quote(name, 'utf-8')))
    if request.status_code != 200:
        return []
    data = request.json()
    artist_list = data['results']['artists']['hits']
    total_artist = []
    for tmp in artist_list:
        # image可能为None
        image = None
        if 'image' in tmp:
            image = download_pic(tmp['image'])
        art = Artist(tmp['name'], tmp['uri'], image, '', tmp['uri'].split(':')[-1])
        total_artist.append(art)
    logger.info("end query artists")
    return total_artist


# 搜索歌手主页的信息
def homepage(uri, token):
    logger.info("start query homepage")
    HEADERS["Authorization"] = "Bearer " + token
    logger.info(HOME_PAGE_DATA_URL.format(quote(uri, "utf-8")))
    request = requests.get(HOME_PAGE_DATA_URL.format(quote(uri, "utf-8")), headers=HEADERS)
    logger.info(request)
    data = request.json()
    # 所有的专辑
    albums = data['data']['artist']['discography']['albums']['items']
    album_list = []
    # 所有的
    singles = data['data']['artist']['discography']['singles']['items']
    single_list = []
    for album in albums:
        # image可能为None
        if not album or not album['releases']['items']:
            continue
            # url可能为None
        url = None
        if album['releases']['items'][0]['coverArt']['sources']:
            url = download_pic(album['releases']['items'][0]['coverArt']['sources'][0]['url'])
        tmp_album = Album(album['releases']['items'][0]['uri'].split(":")[-1], album['releases']['items'][0]['uri'],
                          album['releases']['items'][0]['name'], url)
        album_list.append(tmp_album)
    for single in singles:
        if not single or not single['releases']['items']:
            continue
        # url可能为None
        url = None
        if single['releases']['items'][0]['coverArt']['sources']:
            url = download_pic(single['releases']['items'][0]['coverArt']['sources'][0]['url'])
        tmp_single = Album(single['releases']['items'][0]['uri'].split(":")[-1], single['releases']['items'][0]['uri'],
                           single['releases']['items'][0]['name'], url)
        single_list.append(tmp_single)
    logger.info("end query homepage")
    return album_list, single_list


# 查询
def album_info(uri, token):
    logger.info("start query album songs")
    HEADERS["Authorization"] = "Bearer " + token
    request = requests.get(ALBUMS_INFO_URL.format(quote(uri, "utf-8")), headers=HEADERS)
    logger.info(request)
    data = request.json()
    if data['data']['album'] is None:
        logger.info("album songs is null!")
        return
    songList = []
    # 歌曲列表
    songs = data['data']['album']['tracksWithUIDS']['items']
    for song in songs:
        tmp_song = Song(song['track']['id'], song['track']['name'], song['track']['uri'])
        songList.append(tmp_song)
    logger.info("end query album songs")
    return songList


if __name__ == '__main__':
    # 所有的歌曲
    artist_list = []
    # 首先需要获取token
    token = get_access_token()
    logger.info(token)
    # 进行遍历
    artist = 'little'
    logger.info("artiest -> %s ", artist)
    # 查询所有与name有关联的歌手，选取其中一个就行
    all_artists = query(artist, token)
    # 选取其中一个就行
    tmp_artist = all_artists[0]
    logger.info("relation artist -> %s", tmp_artist.name)
    artist_list.append(tmp_artist)
    name = tmp_artist.name
    id = tmp_artist.id
    uri = tmp_artist.uri
    # 开始查询歌手的专辑列表
    albums_singles = homepage(uri, token)
    for tmp in albums_singles:
        logger.info("albums_singles albums_singles -> %s", tmp)
    # 专辑
    albums = albums_singles[0]
    tmp_artist.albums = albums
    # 单曲
    singles = albums_singles[1]
    tmp_artist.singles = singles
    for album in albums:
        logger.info("album name -> %s", album.name)
        song_list = album_info(album.uri, token)
        album.songs = song_list
    for single in singles:
        logger.info("singles name -> %s", single.name)
        song_list = album_info(single.uri, token)
        single.songs = song_list
